package org.jeecg.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.entity.CustomDeptUnifiedPermission;
import org.jeecg.modules.system.service.ICustomDeptUnifiedPermissionService;
import org.jeecg.modules.system.entity.CustomDeptUnifiedPermission;
import org.jeecg.modules.system.entity.CustomThreadRecord;
import org.jeecg.modules.system.service.ICustomDeptUnifiedPermissionService;
import org.jeecg.modules.system.service.ICustomThreadRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 部门统一权限表
 * @Author: jeecg-boot
 * @Date: 2021-12-18
 * @Version: V1.0
 */
@Api(tags = "部门统一权限表")
@RestController
@RequestMapping("/custom/deptUnifiedPermission")
@Slf4j
public class CustomDeptUnifiedPermissionController extends JeecgController<CustomDeptUnifiedPermission, ICustomDeptUnifiedPermissionService> {
    @Autowired
    private ICustomDeptUnifiedPermissionService zhxfDeptUnifiedPermissionService;
    @Autowired
    private ICustomThreadRecordService threadRecordService;

    /**
     * 分页列表查询
     *
     * @param zhxfDeptUnifiedPermission
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "部门统一权限表-分页列表查询")
    @ApiOperation(value = "部门统一权限表-分页列表查询", notes = "部门统一权限表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CustomDeptUnifiedPermission zhxfDeptUnifiedPermission,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<CustomDeptUnifiedPermission> queryWrapper = QueryGenerator.initQueryWrapper(zhxfDeptUnifiedPermission, req.getParameterMap());
        Page<CustomDeptUnifiedPermission> page = new Page<CustomDeptUnifiedPermission>(pageNo, pageSize);
        IPage<CustomDeptUnifiedPermission> pageList = zhxfDeptUnifiedPermissionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查询角色授权
     *
     * @return
     */
    @RequestMapping(value = "/queryDeptPermission", method = RequestMethod.GET)
    public Result<List<String>> queryRolePermission() {
        Result<List<String>> result = new Result<>();
        try {
            List<CustomDeptUnifiedPermission> list = zhxfDeptUnifiedPermissionService.list();
            result.setResult(list.stream().map(SysRolePermission -> String.valueOf(SysRolePermission.getPermissionId())).collect(Collectors.toList()));
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 保存部门统一权限
     *
     * @return
     */
    @RequestMapping(value = "/saveDeptPermission", method = RequestMethod.POST)
    //@RequiresRoles({ "admin" })
    public Result<String> saveDeptPermission(@RequestBody JSONObject json) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            int threadRecordCount = threadRecordService.count(Wrappers.lambdaQuery(CustomThreadRecord.class).eq(CustomThreadRecord::getThreadType, "dept").eq(CustomThreadRecord::getThreadState, 0));
            if (threadRecordCount > 0) {
                result.error500("有正在执行线程无法授权！");
            } else {
                new Thread(() -> {
                    String permissionIds = json.getString("permissionIds");
                    String lastPermissionIds = json.getString("lastpermissionIds");
                    permission(permissionIds, lastPermissionIds, start);
                }).start();
                result.success("加入线程执行！");
            }
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }

    private void permission(String permissionIds, String lastPermissionIds, long start) {
        CustomThreadRecord threadRecord = new CustomThreadRecord("dept", "更新部门统一权限", 0);
        threadRecordService.save(threadRecord);
        this.zhxfDeptUnifiedPermissionService.savePermission(permissionIds, lastPermissionIds);
//		 log.info("=========耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        threadRecord.setThreadState(1);
        threadRecord.setThreadTime("耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        threadRecordService.updateById(threadRecord);
    }

    /**
     * 添加
     *
     * @param zhxfDeptUnifiedPermission
     * @return
     */
    @AutoLog(value = "部门统一权限表-添加")
    @ApiOperation(value = "部门统一权限表-添加", notes = "部门统一权限表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CustomDeptUnifiedPermission zhxfDeptUnifiedPermission) {
        zhxfDeptUnifiedPermissionService.save(zhxfDeptUnifiedPermission);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param zhxfDeptUnifiedPermission
     * @return
     */
    @AutoLog(value = "部门统一权限表-编辑")
    @ApiOperation(value = "部门统一权限表-编辑", notes = "部门统一权限表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CustomDeptUnifiedPermission zhxfDeptUnifiedPermission) {
        zhxfDeptUnifiedPermissionService.updateById(zhxfDeptUnifiedPermission);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "部门统一权限表-通过id删除")
    @ApiOperation(value = "部门统一权限表-通过id删除", notes = "部门统一权限表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        zhxfDeptUnifiedPermissionService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "部门统一权限表-批量删除")
    @ApiOperation(value = "部门统一权限表-批量删除", notes = "部门统一权限表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.zhxfDeptUnifiedPermissionService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "部门统一权限表-通过id查询")
    @ApiOperation(value = "部门统一权限表-通过id查询", notes = "部门统一权限表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CustomDeptUnifiedPermission zhxfDeptUnifiedPermission = zhxfDeptUnifiedPermissionService.getById(id);
        if (zhxfDeptUnifiedPermission == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(zhxfDeptUnifiedPermission);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param zhxfDeptUnifiedPermission
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CustomDeptUnifiedPermission zhxfDeptUnifiedPermission) {
        return super.exportXls(request, zhxfDeptUnifiedPermission, CustomDeptUnifiedPermission.class, "部门统一权限表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CustomDeptUnifiedPermission.class);
    }

}
